<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace addons\cloud_market\controller\api\docs;

use addons\cloud_market\controller\api\CloudMarketApiController;
use addons\cloud_market\model\CloudMarketDocs;
use addons\cloud_market\model\CloudMarketDocsContent;
use hiduoke\services\FormBuilder as Form;

class Content extends CloudMarketApiController
{
    protected $notApiCheck = ['*'];

    protected $notApiLogin = ['getContentById', 'verifyKeyword'];

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new CloudMarketDocsContent();
    }

    // 获取文档内容列表
    public function getListByDocsId($docs_id)
    {
        $user_id = $this->getUser()['id'] ?? 0;
        $docs = (new CloudMarketDocs())->where(['user_id' => $user_id, 'id' => $docs_id])->find();
        if (!$docs) {
            return $this->error('未找到文档或你没有权限');
        }
        $list = $this->model->where(['docs_id' => $docs_id])->field(['id', 'name'])->select();
        return $this->success('success', $list);
    }

    // 添加文档内容
    public function addContent()
    {
        $data = array(
            'name'    => $this->request->param('name'),
            'docs_id' => $this->request->param('docs_id'),
        );
        $this->model->save($data);
        return $this->success('success');
    }

    // 更新文档内容
    public function updateContent()
    {
        $res = $this->model->where(['id' => $this->request->param('id')])->find();
        if (!$res) {
            return $this->error('未找到文档内容');
        }
        $res->content = $this->request->param('content');
        $res->save();
        return $this->success('success');
    }

    public function getContentById()
    {
        $res = $this->model->where(['id' => $this->request->param('id')])->find();
        if (!$res) {
            return $this->error('未找到文档内容');
        }
        return $this->success('success', $res);
    }

    // 删除文档内容
    public function delete($id)
    {
        $res = $this->model->where(['id' => $id])->find();
        if (!$res) {
            return $this->error('未找到文档内容');
        }
        $res->delete();
        return $this->success('success');
    }

    public function getByDocsId()
    {
        $list = $this->model->where('docs_id', $this->request->param('docs_id'))->select();
        return $this->success('success', $list);
    }

    public function getForm($id, $docs_id)
    {
        $row = $this->model->findOrEmpty($id);//创建表单
        $form = Form::createForm("/api.docs.content/save?id=" . $id)->setMethod("POST");
        $user = $this->getUser();
        $docs = (new CloudMarketDocs())->where(['user_id' => $user['id'], 'id' => $docs_id])->find();
        if (!$docs) {
            return $this->error('未找到文档或你没有权限');
        }
        $dev_id = $user['developer']['id'] ?? 0;
        if (!$dev_id) {
            return $this->error('仅开发者可创建文档');
        }
        $option = [
            ['label' => '公开', 'value' => 'public'],
            ['label' => '登录可见', 'value' => 'login'],
            ['label' => '购买模块可见', 'value' => 'addon'],
            ['label' => '口令访问可见', 'value' => 'keyword'],
            // public=公开,login=登录,dev=开发者,addon=购买模块,keyword=口令访问
            // enum('public','login','dev','addon','keyword')
        ];
        if ($user['id'] == 1) {
            $option[] = ['label' => '开发者可见', 'value' => 'dev'];
        }
        //新增表单
        $rule = [
            Form::hidden('docs_id', $docs_id),
            Form::input('name', '目录标题', $row['name'] ?? '')->required(),
            Form::number('sort', '排序', $row['sort'] ?? '')->required(),
            // 访问权限
            Form::select('access', '访问权限', $row['access'] ?? '')->options($option)->appendControl('keyword', [
                Form::input('keyword', '目录密码', $row['keyword'] ?? '')
                    ->effect(['help' => '设置访问当前文档目录的密码，不设置则不需要密码访问']),
            ]),
        ];
        $title = !$id ? "新增" : "编辑";
        $form->setTitle($title)->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }


    public function save($id = 0)
    {
        $user = $this->getUser();
        $row = $this->model->findOrEmpty($id);
//        if ($id && $row['user_id'] != $user['id']) {
//            return $this->error('非法操作,你没有权限');
//        }
        if ($row->isEmpty()) {
            $formData = getFormData();
            $formData['content'] = "# " . $formData['name'];
        } else {
            if ($row['user_id'] == $user['id'] || $user['id'] == 1) {
                $formData = getFormData();
            } else {
                return $this->error('非法操作,你没有权限');
            }
        }

//
//        $formData = getFormData();
//        if(!$id){
//            $formData['content'] = "# " . $formData['name'];
//        }
        $row->save($formData);
        return $this->success("保存成功", $formData);
    }


    public function verifyKeyword($content_id, $keyword)
    {
        $content = $this->model->where(['id' => $content_id])->find();
        if ($content['keyword'] != $keyword) {
            return $this->error('口令错误');
        } else {
            return $this->success('口令正确', $content);
        }
    }
}
